import { app, BrowserWindow, ipcMain, globalShortcut } from 'electron';
import * as path from 'path';
import WindowsLocker from './windows-locker';
import LinuxLocker from './linux-locker';

// 类型定义
interface ExamModeStatus {
    isExamMode: boolean;
}

interface OSInfo {
    platform: string;
    isLinux: boolean;
    isWindows: boolean;
    isDeepin: boolean;
}

// 全局变量
let isExamMode: boolean = false;
let mainWindow: BrowserWindow | null = null;
let systemLocker: WindowsLocker | LinuxLocker | null = null;

const isDev: boolean = !app.isPackaged || process.env.NODE_ENV === 'development';
const isLinux: boolean = process.platform === 'linux';
const isWindows: boolean = process.platform === 'win32';

function createWindow(): BrowserWindow {
    mainWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, 'preload.js')
        }
    });

    const port = process.env.PORT || 5173;
    const devServerUrl = `http://localhost:${port}`;

    if (isDev) {
        console.log(`🚀 开发模式 - 端口: ${port}`);
        mainWindow.loadURL(devServerUrl);
        mainWindow.webContents.openDevTools();
    } else {
        console.log('📦 生产模式');
        mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'));
    }

    // 初始化系统锁定器
    if (isWindows) {
        systemLocker = new WindowsLocker();
        console.log('🪟 Windows 系统锁定器已初始化');
    } else if (isLinux) {
        systemLocker = new LinuxLocker();
        console.log('🐧 Linux 系统锁定器已初始化');
        app.disableHardwareAcceleration();
        app.commandLine.appendSwitch('--disable-gpu');
        app.commandLine.appendSwitch('--disable-software-rasterizer');
    } else {
        console.log('🍎 macOS 或其他系统 - 使用基本锁定');
    }

    return mainWindow;
}

async function enableExamMode(): Promise<void> {
    if (isExamMode) return;
    console.log('🔒 启用考试模式');
    isExamMode = true;

    // 系统级锁定
    if (systemLocker) {
        await systemLocker.enableLock();
    } else {
        enableBasicLock();
    }

    // 窗口锁定
    if (mainWindow) {
        mainWindow.setFullScreen(true);
        mainWindow.setMenu(null);
        mainWindow.setMinimizable(false);
        mainWindow.setMaximizable(false);
        mainWindow.setResizable(false);
        mainWindow.setClosable(false);
        mainWindow.setAlwaysOnTop(true, 'screen-saver');

        mainWindow.on('blur', () => {
            console.log('窗口失去焦点，强制获取焦点');
            mainWindow!.focus();
        });
    }
}

async function disableExamMode(): Promise<void> {
    if (!isExamMode) return;
    console.log('🔓 禁用考试模式');
    isExamMode = false;

    // 系统级解锁
    if (systemLocker) {
        await systemLocker.disableLock();
    }

    globalShortcut.unregisterAll();

    // 窗口解锁
    if (mainWindow) {
        mainWindow.setFullScreen(false);
        mainWindow.setClosable(true);
        mainWindow.setMinimizable(true);
        mainWindow.setMaximizable(true);
        mainWindow.setResizable(true);
        mainWindow.setAlwaysOnTop(false);
    }
}

function enableBasicLock(): void {
    const shortcuts: string[] = [
        'Alt+Tab', 'Alt+F4', 'Ctrl+W', 'Ctrl+F4', 'Escape', 'F11',
        'CommandOrControl+R', 'F5', 'CommandOrControl+Shift+I'
    ];

    shortcuts.forEach(shortcut => {
        const isRegistered = globalShortcut.register(shortcut, () => {
            console.log(`已屏蔽: ${shortcut}`);
            return false;
        });

        if (!isRegistered) {
            console.warn(`无法注册快捷键: ${shortcut}`);
        }
    });
}

// IPC 通信
ipcMain.handle('toggle-exam-mode', async (): Promise<ExamModeStatus> => {
    if (isExamMode) {
        await disableExamMode();
    } else {
        await enableExamMode();
    }
    return { isExamMode };
});

ipcMain.handle('get-exam-mode-status', async (): Promise<ExamModeStatus> => {
    return { isExamMode };
});

ipcMain.handle('get-os-info', async (): Promise<OSInfo> => {
    return {
        platform: process.platform,
        isLinux: isLinux,
        isWindows: isWindows,
        isDeepin: isLinux && process.env.DESKTOP_SESSION === 'deepin'
    };
});

app.whenReady().then(() => {
    createWindow();
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
});

app.on('will-quit', async () => {
    if (isExamMode && systemLocker) {
        await systemLocker.disableLock();
    }
    globalShortcut.unregisterAll();
});

// 导出类型供其他文件使用
export type { ExamModeStatus, OSInfo };